﻿using System;
using System.Linq;
using ITTestingSystem.BusinessLogic.DataServices.Abstract;
using ITTestingSystem.BusinessLogic.TokenService;
using ITTestingSystem.Domain.Entities;

namespace ITTestingSystem.BusinessLogic.DataServices.Concrete
{
    public class UserService : BaseService<User>, IUserService
    {
        private readonly IUserTokenService _userTokenService;

        public UserService(IRepositoryForEntity<User> repository, IUserTokenService userTokenService)
            : base(repository)
        {
            _userTokenService = userTokenService;
        }

        User IUserService.FirstOrDefault(Func<User, bool> predicate)
        {
            return Repository.GetAll().FirstOrDefault(predicate);
        }

        User IUserService.GetUserByEmail(string email)
        {
            return Repository.GetAll().FirstOrDefault(user =>
                string.Compare(user.Email, email, StringComparison.OrdinalIgnoreCase) == 0);
        }

        User IUserService.GetUserByLogin(string login)
        {
            return Repository.GetAll().FirstOrDefault(user =>
                string.Compare(user.AuthenticationsDetail.Login, login, StringComparison.OrdinalIgnoreCase) == 0);
        }

        string IUserService.GetRoleNameByUserName(string username)
        {
            var searchingUser = Repository.GetAll().FirstOrDefault(user => user.AuthenticationsDetail.Login == username);

            return searchingUser == null ? string.Empty : searchingUser.Role.Name;
        }

        User IUserService.GetUserByLoginPassword(string login, string password)
        {
            return Repository.GetAll().FirstOrDefault
                (user =>
                        user.AuthenticationsDetail.Login == login
                        &&
                        user.AuthenticationsDetail.PasswordHash == password
                );
        }

        bool IUserService.UserExist(string email, string login)
        {
            var result = Repository.GetAll().FirstOrDefault
                (user =>
                        user.Email == email
                        ||
                        user.AuthenticationsDetail.Login == login
                );

            return (result != null);
        }

        string IUserService.GetUserToken(User user)
        {
            var token = _userTokenService.GetToken(user.Email);

            return token;
        }

        bool IUserService.SetPasswordConfirm(string token)
        {
            var email = _userTokenService.GetKeyFromToken(token);

            var user = Repository.GetAll().FirstOrDefault(u => u.Email == email);

            if (user == null)
            {
                return false;
            }

            user.AuthenticationsDetail.EmailConfirmed = true;

            Repository.Update(user);
            Repository.Save();

            return true;
        }
    }
}
